import { defineStore } from 'pinia'
import { login } from '@/api/login'
import { setStorage, clearStorage } from '@/utils/storage'

const useUserStore = defineStore('user', {
  state: () => ({
    uid: '',
    name: '',
    sign: '',
  }),
  actions: {
    async useLogin({ username, password }) {
      return new Promise((resolve, reject) => {
        login({ username, password })
          .then((result) => {
            if (result.data.code === 200) {
              const { _id, name, sign } = result.data.data
              console.log({ _id, name, sign })
              this.uid = _id
              this.name = name
              this.sign = sign
              this.setInformation(_id, name, sign)
              resolve(result.data)
            } else {
              console.log('denglshi bai', result.data)
              reject(result.data)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    logout() {
      clearStorage()
      this.$reset()

    },
    setInformation() {
      setStorage('uid', this.uid)
      setStorage('name', this.name)
      setStorage('sign', this.sign)
    },
  },
})

export { useUserStore }
